package me.flyray.bsin.infrastructure.biz;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import me.flyray.bsin.domain.entity.*;
import me.flyray.bsin.domain.entity.Transaction;
import me.flyray.bsin.enums.TransactionType;
import me.flyray.bsin.exception.BusinessException;
import me.flyray.bsin.facade.service.MerchantConfigService;
import me.flyray.bsin.infrastructure.mapper.*;
import me.flyray.bsin.blockchain.transaction.BlockchainTransactionService;

import me.flyray.bsin.payment.channel.wxpay.model.RefundUnifyReq;
import me.flyray.bsin.payment.channel.wxpay.model.UnifyOrderReq;
import me.flyray.bsin.payment.common.AbstractRes;
import me.flyray.bsin.payment.channel.wxpay.WxRefundRes;
import me.flyray.bsin.domain.enums.TransactionStatus;
import me.flyray.bsin.payment.enums.ProfitSharingTypeEnum;
import me.flyray.bsin.payment.enums.PayWayEnum;
import me.flyray.bsin.payment.enums.PayMerchantModeEnum;
import me.flyray.bsin.payment.enums.PayChannelInterfaceEnum;
import me.flyray.bsin.security.domain.LoginUser;
import me.flyray.bsin.utils.BsinSnowflake;
import me.flyray.bsin.utils.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import me.flyray.bsin.context.BsinServiceContext;
import org.apache.commons.collections4.MapUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;

@Service
public class TransactionBiz {


    // 常量定义
    private static final String PRODUCT_PROFIT_SHARING_TYPE = "2";
    private static final String DEFAULT_IP = "127.0.0.1";
    private static final Logger log = LoggerFactory.getLogger(TransactionBiz.class);

    @Autowired
    private TransactionMapper transactionMapper;
    @Autowired
    private TransactionJournalMapper transactionJournalMapper;
    @Autowired
    private ProfitSharingConfigMapper profitSharingConfigMapper;

    @Autowired
    private BlockchainTransactionService blockchainTransactionService;

    @Autowired
    private BlockchainFundCollectionBiz blockchainFundCollectionBiz;

    @DubboReference(version = "${dubbo.provider.version}")
    private MerchantConfigService merchantConfigService;
    @Autowired
    private WalletAccountMapper walletAccountMapper;
    @Autowired
    private WalletMapper walletMapper;


    // 注意：硬编码的 Web3j 实例已移除，现在使用 MultiChainManager 统一管理

    /**
     * 代币转出交易（已优化，使用区块链公共服务）
     * 
     * @param chainIdentifier 链标识（默认为 "bsc"）
     * @param fromAddress 发起地址
     * @param toAddress 接受地址
     * @param contractAddress 合约地址
     * @param amount 交易金额
     * @param decimals 位数
     * @return 交易哈希
     */
    @Async("taskExecutor")
    public String tokenTransfer(String chainIdentifier, String fromAddress, String toAddress, String contractAddress, BigInteger amount, Integer decimals) throws Exception {
        log.info("开始代币转账，chain: {}, from: {}, to: {}, contract: {}, amount: {}",
                chainIdentifier, fromAddress, toAddress, contractAddress, amount);

        // 根据地址查询私钥
        LambdaQueryWrapper<WalletAccount> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WalletAccount::getAddress, fromAddress);
        WalletAccount fromWalletAccount = walletAccountMapper.selectOne(queryWrapper);

        // 查询账户对应的钱包
        Wallet wallet = walletMapper.selectById(fromWalletAccount.getWalletNo());

        // 使用区块链公共服务进行代币转账
        return blockchainTransactionService.tokenTransfer(chainIdentifier, fromAddress, wallet.getType(), fromWalletAccount.getPrivateKey(), toAddress, contractAddress, amount, decimals);
    }

    /**
     * ETH转出交易（已优化，使用区块链公共服务）
     * 
     * @param chainIdentifier 链标识
     * @param fromAddress 发起地址
     * @param toAddress 接受地址
     * @param amount ETH数量（Wei）
     * @return 交易哈希
     */
    public String ethTransfer(String chainIdentifier, String fromAddress, String toAddress, BigInteger amount) throws Exception {
        log.info("开始ETH转出交易，chain: {}, fromAddress:{}, toAddress:{}, amount:{}",
                chainIdentifier, fromAddress, toAddress, amount);
        
        // 使用区块链公共服务进行ETH转账
        return blockchainTransactionService.ethTransfer(chainIdentifier, fromAddress, "", toAddress, amount);
    }

    // 注意：签名方法已迁移到 BlockchainTransactionService 中，使用统一的 MPC 签名服务

    /**
     * 查询代币余额（已优化，使用区块链公共服务）
     * 
     * @param chainIdentifier 链名称
     * @param contractAddress 代币合约地址
     * @param holderAddress 代币持有者地址
     * @return 代币余额
     */
    public BigInteger getTokenBalance(String chainIdentifier, String contractAddress, String holderAddress) throws Exception {
        log.info("查询代币余额，chain: {}, contract: {}, holder: {}", chainIdentifier, contractAddress, holderAddress);
        
        // 使用区块链公共服务查询代币余额
        return blockchainTransactionService.getTokenBalance(chainIdentifier, contractAddress, holderAddress);
    }

    /**
     * 用户充值资金归集流程入口
     * 流程步骤：
     * 1. 验证归集参数
     * 2. 调用区块链资金归集业务服务
     * 3. 启动完整的gas提供和资金归集流程
     * 
     * @param chainIdentifier 链标识
     * @param fromAddress 用户地址
     * @param gatherAccountAddress 归集地址
     * @param contractAddress 代币合约地址
     * @param amount 归集金额
     * @param decimals 代币精度
     */
    public void startUserFundCollectionProcess(String chainIdentifier, String fromAddress, String gatherAccountAddress, String contractAddress, BigInteger amount, Integer decimals) {
        log.info("启动用户充值资金归集流程: chain={}, from={}, to={}, amount={}", 
                chainIdentifier, fromAddress, gatherAccountAddress, amount);
        
        // 参数验证
        if (chainIdentifier == null || fromAddress == null || gatherAccountAddress == null || 
            contractAddress == null || amount == null || decimals == null) {
            log.error("归集参数验证失败，存在空值参数: chain={}, from={}, to={}",
                    chainIdentifier, fromAddress, gatherAccountAddress);
            throw new IllegalArgumentException("资金归集参数不能为空");
        }
        
        if (amount.compareTo(BigInteger.ZERO) <= 0) {
            log.error("归集金额验证失败: amount={}", amount);
            throw new IllegalArgumentException("归集金额必须大于0");
        }
        
        try {
            blockchainFundCollectionBiz.startFundCollectionProcess(chainIdentifier, fromAddress, gatherAccountAddress, contractAddress, amount, decimals);
            log.info("资金归集流程启动成功: from={}, amount={}", fromAddress, amount);
        } catch (Exception e) {
            log.error("资金归集流程启动失败: chain={}, from={}, error={}",
                    chainIdentifier, fromAddress, e.getMessage(), e);
            throw e;
        }
    }

    /**
     * 处理Gas交易确认事件通知
     * 
     * @param mQMsg 消息对象
     */
    public void handleGasTransactionConfirmationEvent(JSONObject mQMsg) {
        log.info("处理gas加油确认MQ消息: {}", mQMsg.toString());
        
        try {
            String chainIdentifier = mQMsg.getString("chainIdentifier");
            String gasTxHash = mQMsg.getString("gasTxHash");
            String fromAddress = mQMsg.getString("fromAddress");
            String toAddress = mQMsg.getString("toAddress");
            String contractAddress = mQMsg.getString("contractAddress");
            String amountStr = mQMsg.getString("amount");
            String decimalsStr = mQMsg.getString("decimals");
            
            // 验证关键参数
            if (chainIdentifier == null || chainIdentifier.trim().isEmpty()) {
                log.error("chainIdentifier为空，拒绝处理: {}", mQMsg.toString());
                throw new IllegalArgumentException("chainIdentifier不能为空");
            }
            
            if (gasTxHash == null || gasTxHash.trim().isEmpty()) {
                log.error("gasTxHash为空，无法查询交易状态");
                throw new IllegalArgumentException("gasTxHash不能为空");
            }

            // 转换数值类型
            BigDecimal amount;
            Integer decimals;
            try {
                amount = new BigDecimal(amountStr);
                decimals = Integer.valueOf(decimalsStr);
            } catch (NumberFormatException e) {
                log.error("数值格式错误: amount={}, decimals={}", amountStr, decimalsStr);
                throw new IllegalArgumentException("数值格式错误", e);
            }
            
            // 验证chainIdentifier的有效值
            if (!isValidChainIdentifier(chainIdentifier)) {
                log.error("无效的链标识符: {}", chainIdentifier);
                throw new IllegalArgumentException("无效的链标识符: " + chainIdentifier);
            }
            
            log.info("处理gas确认: chain={}, gasTxHash={}, from={}, amount={}", 
                    chainIdentifier, gasTxHash, fromAddress, amount);
            
            blockchainFundCollectionBiz.handleGasTransactionConfirmationEvent(
                    chainIdentifier, gasTxHash, fromAddress, toAddress, contractAddress, 
                    amount.toBigInteger(), decimals);
                    
            log.info("gas加油确认处理完成: gasTxHash={}", gasTxHash);
                    
        } catch (Exception e) {
            log.error("处理gas加油确认失败: error={}", e.getMessage(), e);
            throw e;
        }
    }
    
    /**
     * 验证链标识符是否有效
     */
    private boolean isValidChainIdentifier(String chainIdentifier) {
        if (chainIdentifier == null) {
            return false;
        }
        
        String lowerChainId = chainIdentifier.toLowerCase().trim();
        return lowerChainId.equals("ethereum") || 
               lowerChainId.equals("bsc") || 
               lowerChainId.equals("polygon") || 
               lowerChainId.equals("conflux");
    }

    /**
     * 处理资金归集确认事件通知
     * 
     * @param mQMsg 消息对象
     */
    public void handleFundCollectionConfirmationEventNotify(JSONObject mQMsg) {
        log.info("处理资金归集确认MQ消息: {}", mQMsg.toString());
        
        try {
            String chainIdentifier = mQMsg.getString("chainIdentifier");
            String collectionTxHash = mQMsg.getString("collectionTxHash");
            
            // 验证关键参数
            if (chainIdentifier == null || chainIdentifier.trim().isEmpty()) {
                log.error("chainIdentifier为空，拒绝处理: {}", mQMsg.toString());
                throw new IllegalArgumentException("chainIdentifier不能为空");
            }
            
            if (collectionTxHash == null || collectionTxHash.trim().isEmpty()) {
                log.error("collectionTxHash为空，无法查询交易状态");
                throw new IllegalArgumentException("collectionTxHash不能为空");
            }
            
            // 验证chainIdentifier的有效值
            if (!isValidChainIdentifier(chainIdentifier)) {
                log.error("无效的链标识符: {}", chainIdentifier);
                throw new IllegalArgumentException("无效的链标识符: " + chainIdentifier);
            }
            
            log.info("处理归集确认: chain={}, collectionTxHash={}", chainIdentifier, collectionTxHash);
            
            blockchainFundCollectionBiz.handleFundCollectionConfirmationEvent(chainIdentifier, collectionTxHash);
            
            log.info("资金归集确认处理完成: collectionTxHash={}", collectionTxHash);
            
        } catch (Exception e) {
            log.error("处理资金归集确认失败: error={}", e.getMessage(), e);
            throw e;
        }
    }

    /**
     * 创建或获取交易订单，并处理分账配置
     * @param loginUser
     * @param unifyOrderReq
     * @return 交易订单
     */
    public Transaction createWithProfitSharing(LoginUser loginUser,UnifyOrderReq unifyOrderReq) {

        log.info("开始创建或获取交易订单，outOrderNo: {}", unifyOrderReq.getOutOrderNo());

        // 查询是否已存在交易订单
        Transaction waasTransaction = transactionMapper.selectOne(
                new LambdaQueryWrapper<Transaction>().eq(Transaction::getOutOrderNo, unifyOrderReq.getOutOrderNo()));

        // 如果交易不存在，创建新交易
        if (waasTransaction == null) {
            log.info("创建新交易订单，outOrderNo: {}", unifyOrderReq.getOutOrderNo());
            waasTransaction = new Transaction();
            waasTransaction.setSerialNo(BsinSnowflake.getId());
            waasTransaction.setOutOrderNo(unifyOrderReq.getOutOrderNo());
            waasTransaction.setTransactionType(TransactionType.PAY.getCode());
            waasTransaction.setComment(unifyOrderReq.getRemark());
            waasTransaction.setTxAmount(unifyOrderReq.getPayAmount());
            waasTransaction.setFromAddress(unifyOrderReq.getCustomerNo());
            waasTransaction.setToAddress(unifyOrderReq.getMerchantNo());
            waasTransaction.setBizRoleType(loginUser.getBizRoleType());
            waasTransaction.setBizRoleTypeNo(loginUser.getBizRoleTypeNo());
            waasTransaction.setTenantId(loginUser.getTenantId());
            waasTransaction.setCreateTime(new java.util.Date());
            waasTransaction.setCreateBy(loginUser.getCreateBy());

            // 处理分账配置
            boolean needProfitSharing = processProfitSharingConfig(
                    waasTransaction, unifyOrderReq.getProfitSharingType(), unifyOrderReq.getProfitSharingAmount(),
                    unifyOrderReq.getMerchantNo(), loginUser.getTenantId(), unifyOrderReq.getPayAmount());

            waasTransaction.setProfitSharing(needProfitSharing);
            transactionMapper.insert(waasTransaction);
            log.info("交易订单创建成功，transactionNo: {}", waasTransaction.getSerialNo());
        }

        return waasTransaction;
    }

    /**
     * 处理分账配置逻辑
     *
     * @param transaction 交易对象
     * @param profitSharingType 分账类型
     * @param profitSharingAmount 分账金额字符串
     * @param merchantNo 商户号
     * @param tenantId 租户ID
     * @param payAmount 支付金额
     * @return 是否需要分账
     */
    private boolean processProfitSharingConfig(Transaction transaction, String profitSharingType,
            BigDecimal profitSharingAmount, String merchantNo, String tenantId, BigDecimal payAmount) {

        boolean needProfitSharing = false;

        if (ProfitSharingTypeEnum.BY_PRODUCT.getCode().equals(profitSharingType)) {
            // 基于商品进行分账
            if (profitSharingAmount!= null) {
                needProfitSharing = true;
                transaction.setProfitSharingAmount(profitSharingAmount);
                transaction.setProfitSharingType(profitSharingType);
                log.debug("基于商品分账，分账金额: {}", profitSharingAmount.toString());
            }
        } else {
            // 查询商户让利配置
            Map<String, Object> requestMap = new HashMap<>();
            requestMap.put("","");
            MerchantConfig merchantConfig = merchantConfigService.getDetail(requestMap);

            ProfitSharingConfig profitSharingConfig = profitSharingConfigMapper.selectOne(
                new LambdaQueryWrapper<ProfitSharingConfig>()
                    .eq(ProfitSharingConfig::getTenantId, tenantId));

            if (profitSharingConfig != null) {
                needProfitSharing = true;
                java.math.BigDecimal calculatedAmount = merchantConfig.getProfitSharingRate()
                    .multiply(payAmount);
                transaction.setProfitSharingAmount(calculatedAmount);
                transaction.setProfitSharingType(profitSharingType);
                log.debug("基于商户让利配置分账，分账金额: {}", calculatedAmount);
            }
        }

        return needProfitSharing;
    }


    /**
     * 构建统一支付请求对象
     * @param loginUser
     * @param requestMap
     * @return UnifyOrderReq
     */
    public UnifyOrderReq buildUnifyOrderReq(LoginUser loginUser, Map<String, Object> requestMap) {
        UnifyOrderReq unifyOrderReq = BsinServiceContext.getReqBodyDto(UnifyOrderReq.class, requestMap);
         // 用户信息
         unifyOrderReq.setChannelUserId(unifyOrderReq.getChannelUserId());
         unifyOrderReq.setClientIp(MapUtils.getString(requestMap, "clientIp", DEFAULT_IP));
         // 时间配置
         unifyOrderReq.setExpiredTimeDate(DateUtils.addMinutes(new Date(), 10));
         // 分账配置
         if (PRODUCT_PROFIT_SHARING_TYPE.equals(unifyOrderReq.getProfitSharingType())) {
             unifyOrderReq.setDivisionMode(1); // 自动分账
         }
        return unifyOrderReq;
    }


    /**
     * 构建统一退款请求对象
     * @param loginUser 登录用户
     * @param requestMap 请求参数
     * @param originalTransaction 原始交易记录
     * @param refundSerialNo 退款序列号
     * @return RefundUnifyReq
     */
    public RefundUnifyReq buildRefundUnifyReq(LoginUser loginUser, Map<String, Object> requestMap, 
                                              Transaction originalTransaction, String refundSerialNo) {
        // 直接构建RefundUnifyReq，不再通过RefundOrderReq中转
        RefundUnifyReq refundUnifyReq = BsinServiceContext.getReqBodyDto(RefundUnifyReq.class, requestMap);
        
        // 基本信息
        refundUnifyReq.setOutTradeNo(originalTransaction.getOutOrderNo());
        refundUnifyReq.setOutRefundNo(refundSerialNo);
        refundUnifyReq.setTransactionId(originalTransaction.getTxHash());
        refundUnifyReq.setTotalAmount(originalTransaction.getTxAmount());
        if (StringUtils.isBlank(refundUnifyReq.getCurrency())) {
            refundUnifyReq.setCurrency("CNY");
        }
        
        // 支付渠道信息（从原始交易中获取）
        refundUnifyReq.setPayChannel(PayChannelInterfaceEnum.WXPAY.getCode());
        refundUnifyReq.setPayWay(PayWayEnum.WX_LITE.getCode()); // 默认小程序，实际应该从原始交易获取
        refundUnifyReq.setPayChannelConfigNo(originalTransaction.getPayChannelConfigNo());
        
        // 商户信息
        refundUnifyReq.setBizRoleTypeNo(originalTransaction.getBizRoleTypeNo());
        if (StringUtils.isBlank(refundUnifyReq.getMerchantPayMode())) {
            refundUnifyReq.setMerchantPayMode(PayMerchantModeEnum.NORMAL_MERCHANT_MODE.getCode());
        }
        
        // 其他信息
        if (StringUtils.isBlank(refundUnifyReq.getClientIp())) {
            refundUnifyReq.setClientIp(MapUtils.getString(requestMap, "clientIp", DEFAULT_IP));
        }
        refundUnifyReq.setTenantId(originalTransaction.getTenantId());
        
        return refundUnifyReq;
    }

    /**
     * 创建退款交易记录
     * 
     * @param loginUser 登录用户
     * @param refundUnifyReq 退款请求对象
     * @param originalTransaction 原始交易记录
     * @return Transaction 退款交易记录
     */
    public Transaction createRefundTransaction(LoginUser loginUser, RefundUnifyReq refundUnifyReq, Transaction originalTransaction) {
        log.info("开始创建退款交易记录，outRefundNo: {}", refundUnifyReq.getOutRefundNo());
        
        // 查询是否已存在退款交易记录
        Transaction refundTransaction = transactionMapper.selectOne(new LambdaQueryWrapper<Transaction>()
                .eq(Transaction::getOutOrderNo, refundUnifyReq.getOutRefundNo())
                .eq(Transaction::getTransactionType, TransactionType.REFUND.getCode()));
        
        if (refundTransaction == null) {
            log.info("退款交易记录不存在，创建新记录，outRefundNo: {}", refundUnifyReq.getOutRefundNo());
            refundTransaction = new Transaction();
            refundTransaction.setSerialNo(refundUnifyReq.getOutRefundNo());
            refundTransaction.setOutOrderNo(refundUnifyReq.getOutRefundNo());
            refundTransaction.setTransactionType(TransactionType.REFUND.getCode());
            refundTransaction.setTxAmount(refundUnifyReq.getRefundAmount());
            refundTransaction.setTransactionStatus(TransactionStatus.PENDING.getCode());
            refundTransaction.setComment(refundUnifyReq.getRefundReason());
            refundTransaction.setBizRoleType(loginUser.getBizRoleType());
            refundTransaction.setBizRoleTypeNo(loginUser.getBizRoleTypeNo());
            refundTransaction.setTenantId(originalTransaction.getTenantId());
            refundTransaction.setCreateTime(new Date());
            refundTransaction.setCreateBy(loginUser.getUserId());
            transactionMapper.insert(refundTransaction);
            log.info("退款交易记录创建成功，refundSerialNo: {}", refundUnifyReq.getOutRefundNo());
        } else {
            log.info("退款交易记录已存在，更新记录，outRefundNo: {}", refundUnifyReq.getOutRefundNo());
            refundTransaction.setTxAmount(refundUnifyReq.getRefundAmount());
            if (!refundTransaction.getTransactionStatus().equals(TransactionStatus.SUCCESS.getCode())) {
                refundTransaction.setTransactionStatus(TransactionStatus.PENDING.getCode());
                refundTransaction.setComment(refundUnifyReq.getRefundReason());
                transactionMapper.updateById(refundTransaction);
            }
        }
        
        return refundTransaction;
    }

    /**
     * 创建退款流水记录
     * 
     * @param refundTransaction 退款交易记录
     * @param refundAmount 退款金额
     */
    public void createRefundJournal(Transaction refundTransaction, BigDecimal refundAmount) {
        log.info("开始创建退款流水记录，transactionNo: {}", refundTransaction.getSerialNo());
        
        TransactionJournal refundJournal = transactionJournalMapper.selectOne(
                new LambdaQueryWrapper<TransactionJournal>()
                        .eq(TransactionJournal::getTransactionNo, refundTransaction.getSerialNo()));

        if (refundJournal == null) {
            // 创建新的退款流水记录
            refundJournal = new TransactionJournal();
            refundJournal.setTransactionNo(refundTransaction.getSerialNo());
            refundJournal.setPayAmount(refundAmount);
            refundJournal.setSerialNo(BsinSnowflake.getId());
            refundJournal.setStatus(TransactionStatus.PENDING.getCode());
            transactionJournalMapper.insert(refundJournal);
            log.info("退款流水记录创建成功，journalNo: {}", refundJournal.getSerialNo());
        }
    }

    /**
     * 根据退款响应更新交易记录
     * 
     * @param refundTransaction 退款交易记录
     * @param response 退款响应
     * @param originalTransaction 原始交易记录
     */
    public void updateRefundTransactionFromResponse(Transaction refundTransaction, AbstractRes response, Transaction originalTransaction) {
        log.info("开始更新退款交易记录，refundSerialNo: {}", refundTransaction.getSerialNo());
        
        if (response instanceof WxRefundRes) {
            WxRefundRes wxRefundRes = (WxRefundRes) response;
            
            // 更新微信退款单号
            if (StringUtils.isNotBlank(wxRefundRes.getRefundId())) {
                refundTransaction.setTxHash(wxRefundRes.getRefundId());
            }
            
            // 更新退款金额（如果微信返回了实际退款金额）
            if (wxRefundRes.getAmount() != null && wxRefundRes.getAmount().getRefund() != null) {
                BigDecimal actualRefundAmount = new BigDecimal(wxRefundRes.getAmount().getRefund()).divide(new BigDecimal("100"));
                refundTransaction.setTxAmount(actualRefundAmount);
            }
            
            // 更新完成时间
            if ("SUCCESS".equals(wxRefundRes.getStatus()) && StringUtils.isNotBlank(wxRefundRes.getSuccessTime())) {
                try {
                    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    refundTransaction.setCompletedTime(sdf.format(new Date()));
                } catch (Exception e) {
                    log.warn("解析微信退款完成时间失败: {}", wxRefundRes.getSuccessTime(), e);
                    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    refundTransaction.setCompletedTime(sdf.format(new Date()));
                }
            }
            
            log.info("更新退款交易记录完成，refundSerialNo: {}, wxRefundId: {}, status: {}", 
                    refundTransaction.getSerialNo(), wxRefundRes.getRefundId(), wxRefundRes.getStatus());
        }
        
        // 设置支付渠道配置号
        refundTransaction.setPayChannelConfigNo(originalTransaction.getPayChannelConfigNo());
        // 更新修改时间
        refundTransaction.setUpdateTime(new Date());
    }

    /**
     * 验证退款前置条件
     * 
     * @param originalTransaction 原始交易记录
     * @param refundUnifyReq 退款请求
     */
    public void validateRefundConditions(Transaction originalTransaction, RefundUnifyReq refundUnifyReq) {
        log.info("开始验证退款条件，outTradeNo: {}", refundUnifyReq.getOutTradeNo());
        
        if (originalTransaction == null) {
            log.error("原交易订单不存在，outTradeNo: {}", refundUnifyReq.getOutTradeNo());
            throw new BusinessException("100000", "原交易订单不存在，outTradeNo: " + refundUnifyReq.getOutTradeNo());
        }
        
        // 验证订单状态
        if (!TransactionStatus.SUCCESS.getCode().equals(originalTransaction.getTransactionStatus())) {
            log.error("订单状态不允许退款，outTradeNo: {}, status: {}", refundUnifyReq.getOutTradeNo(), originalTransaction.getTransactionStatus());
            throw new BusinessException("100000", "订单状态不允许退款");
        }
        
        // 验证退款金额
        BigDecimal originalAmount = originalTransaction.getTxAmount();
        if (refundUnifyReq.getRefundAmount().compareTo(originalAmount) > 0) {
            log.error("退款金额不能大于原订单金额，outTradeNo: {}, originalAmount: {}, refundAmount: {}",
                    refundUnifyReq.getOutTradeNo(), originalAmount, refundUnifyReq.getRefundAmount());
            throw new BusinessException("100000", "退款金额不能大于原订单金额");
        }
        
        log.info("退款条件验证通过，outTradeNo: {}", refundUnifyReq.getOutTradeNo());
    }

}
